package Server;

import Data.*;
import Email.EmailCaptcha;
import Email.ManageCaptcha;
import Email.SendCaptcha;
import MyInterfaces.MassageType;
import Search.SearchCommonSentence;
import Search.UserInitStage;

import java.io.*;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

public class LoginServer implements Runnable{

    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";
    private ServerSocket serverSocket;
    private Socket socket;
    private static String userid;

    public LoginServer(ServerSocket serverSocket, Socket socket) {
        this.serverSocket = serverSocket;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

        System.out.println("连接数据库");
        Connection Conn = DriverManager.getConnection(url, user, password);
        //数据库的访问
        String sql = "select *FROM userinformation where id=? and userPwd=?;";
        System.out.println(sql);
        PreparedStatement operation = null;
        operation = Conn.prepareStatement(sql);
        ObjectInputStream reader;
        while(true)
        {
            reader=new ObjectInputStream(socket.getInputStream());
            event massage=(event) reader.readObject();
            //请求登录
            if(massage.getType().equals(MassageType.Request_Login))
            {
                LoginData loginData= (LoginData) massage.getT();
                if(ManageClientConnectionServerThread.existId(loginData.getId()))
                {
                    System.out.println("重复登录");
                    event returnmassage=new event();
                    returnmassage.setType(MassageType.Return_Repeat_Login);
                    ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
                    writer.writeObject(returnmassage);
                    writer.flush();
                    continue;
                }
                //开始查询
                operation.setString(1, loginData.getId());
                String privatepassword=getMD5(loginData.getUserPwd());
                operation.setString(2, privatepassword);
                ResultSet resultSet = operation.executeQuery();
                ResultSetMetaData md=resultSet.getMetaData();
                if(!resultSet.next())
                {
                    //说明账号密码出错
                    event returnmassage=new event();
                    returnmassage.setType(MassageType.Return_Login_Fail);
                    ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
                    writer.writeObject(returnmassage);
                    writer.flush();
                }
                else
                {
                    resultSet.close();
                    operation.close();
                    Conn.close();
                    //新建一个关于自己的数据
                    UserInitStage userInitStage=new UserInitStage(loginData.getId());
                    FriendListData friendListData=userInitStage.userInformation();
//                //    发送出去
                    ObjectOutputStream writer=new ObjectOutputStream(socket.getOutputStream());
                    event returnmassage=new event();
                    InitChatData initChatData=new InitChatData();
                    returnmassage.setType(MassageType.Return_Init_Information);
                    initChatData.setFriendListData(friendListData);

                    SetAllGroupToUser setAllGroupToUser=new SetAllGroupToUser(loginData.getId());
                    ArrayList<GroupData> arrayList=setAllGroupToUser.setAllGroup();
                    initChatData.setGroupDataArrayList(arrayList);

                    initChatData.setCommmonSentence(new SearchCommonSentence().search(loginData.getId()));

                    returnmassage.setT(initChatData);

                    writer.writeObject(returnmassage);
                    writer.flush();

                    System.out.println("接受客户端发送的消息");
                    ChatServer chatServer=new ChatServer(socket,loginData.getId());

                    //开启一个线程用来接收消息
                    Runnable sendTask=new ChatServer(socket,loginData.getId());
                    Main.executorService.submit(sendTask);
//                    new Thread(chatServer).start();
                    ManageClientConnectionServerThread.addThread(loginData.getId(),chatServer);


                    break;
                //    FriendListData friendListData=returnmassage.ge
                }
            }
            else if(massage.getType().equals(MassageType.Request_Register))
            {
                //注册
                System.out.println("开始注册");
                RegisterServer registerServer=new RegisterServer(serverSocket,socket);
                if(registerServer.register(massage)) break;
            }
            else if(massage.getType().equals(MassageType.Get_Captcha))
            {
                String email=(String) massage.getT();
                //得到验证码
                SendCaptcha sendCaptcha=new SendCaptcha();
                String captcha= sendCaptcha.getYzm(email);
                EmailCaptcha emailCaptcha=new EmailCaptcha(email,captcha,new Date());
                ManageCaptcha.AddCaptchaByEmail(emailCaptcha);
                System.out.println("得到了验证码");
                //加入进去
            }
            else if(massage.getType().equals(MassageType.Request_Reset_Password))
            {
                //重置密码
                ResetPwdServer resetPwdServer=new ResetPwdServer(socket);
                if(resetPwdServer.ResetPwd(massage)) break;
            }
            else if(massage.getType().equals(MassageType.Exit))
            {
                break;
                //如果要退出则关闭socket
             //   socket.close();
            }

        }
        Conn.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public String getMD5(String str) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());
        return new BigInteger(1, md.digest()).toString(16);
    }
}
